<!DOCTYPE html><html lang="zh-CN,en,default"><head hexo-theme="https://github.com/volantis-x/hexo-theme-volantis/tree/4.3.1"><meta charset="utf-8"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><meta name="renderer" content="webkit"><meta name="force-rendering" content="webkit"><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"><meta name="HandheldFriendly" content="True"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><link rel="preload" href="/css/first.css" as="style"><title>Mybatis学习笔记2-映射文件 - Tang&#39;s blog.</title><meta name="keywords" content="Mybatis"><meta name="description" content="cache – 该命名空间的缓存配置。
cache-ref – 引用其它命名空间的缓存配置。
resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。
parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。
sq..."><link rel="alternate" href="/atom.xml" title="Tang's blog." type="application/atom+xml"><meta name="msapplication-TileColor" content="#ffffff"><meta name="msapplication-config" content="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/browserconfig.xml"><meta name="theme-color" content="#ffffff"><link rel="apple-touch-icon" sizes="180x180" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/cf_1o_180x180.png"><link rel="icon" type="image/png" sizes="32x32" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/cf_1o_32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/cf_1o_16x16.png"><link rel="manifest" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/manifest2.json"><link rel="mask-icon" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/cf_image2vector.svg" color="#5bbad5"><link rel="shortcut icon" href="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/favicon/32favicon32.ico"><link rel="stylesheet" href="/css/first.css"><link rel="stylesheet" href="/css/style.css" media="print" onload='this.media="all",this.onload=null'><noscript><link rel="stylesheet" href="/css/style.css"></noscript><script id="loadcss"></script><script>window.MSInputMethodContext&&document.documentMode&&document.write('<style>html{overflow-x: hidden !important;overflow-y: hidden !important;}.kill-ie{text-align:center;height: 100%;margin-top: 15%;margin-bottom: 5500%;}</style><div class="kill-ie"><h1><b>抱歉，您的浏览器无法访问本站</b></h1><h3>微软已经于2016年终止了对 Internet Explorer (IE) 10 及更早版本的支持，<br/>继续使用存在极大的安全隐患，请使用当代主流的浏览器进行访问。</h3><br/><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.microsoft.com/zh-cn/WindowsForBusiness/End-of-IE-support"><strong>了解详情 ></strong></a></div>')</script><noscript><style>html{overflow-x:hidden!important;overflow-y:hidden!important}.kill-noscript{text-align:center;height:100%;margin-top:15%;margin-bottom:5500%}</style><div class="kill-noscript"><h1><b>抱歉，您的浏览器无法访问本站</b></h1><h3>本页面需要浏览器支持（启用）JavaScript</h3><br> <a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.baidu.com/s?wd=启用JavaScript"><strong>了解详情 ></strong></a></div></noscript></head><body><header id="l_header" class="l_header always shadow blur show"><div class="container"><div id="wrapper"><div class="nav-sub"><p class="title"></p><ul class="switcher nav-list-h m-phone" id="pjax-header-nav-list"><li><a id="s-comment" class="fas fa-comments fa-fw" target="_self" href="javascript:void(0)" rel="external nofollow noreferrer"></a></li><li><a id="s-toc" class="s-toc fas fa-list fa-fw" target="_self" href="javascript:void(0)" rel="external nofollow noreferrer"></a></li></ul></div><div class="nav-main"> <a class="title flat-box" target="_self" href="/"><img no-lazy class="logo" src="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/cover/fav/cf_o1x64.jpg"></a><div class="menu navigation"><ul class="nav-list-h m-pc"><li><a class="menuitem flat-box faa-parent animated-hover" href="/" id="home"><i class="fas fa-home fa-fw"></i> Home</a></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-th-list fa-fw"></i> Articles</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/categories/" id="categories"><i class="fas fa-folder-open fa-fw"></i> Categories</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="/tags/" id="tags"><i class="fas fa-tags fa-fw"></i> Tags</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="/archives/" id="archives"><i class="fas fa-archive fa-fw"></i> Archives</a></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-fan faa-spin animated fa-fw"></i> Play</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/catchTheCat/" id="catchTheCat"><i class="fas fa-cat faa-wrench animated-hover fa-fw"></i> Chat Noir</a></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-cog fa-spin fa-fw"></i> Tools</a><ul class="list-v"><li><a class="menuitem flat-box header toggle-mode-btn"><i class="fas fa-moon fa-fw"></i> 暗黑模式</a></li><li></li><li><a class="menuitem flat-box"><i class="fas fa-compact-disc fa-fw music"></i> Music</a><ul class="list-v"><li><div class="aplayer-container"><meting-js theme="#1BCDFC" autoplay="false" volume="0.7" loop="all" order="list" fixed="false" list-max-height="320px" server="netease" type="playlist" id="5472211102" list-folded="true"></meting-js></div></li></ul></li><li></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-info-circle fa-fw"></i> Me</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/about/" id="about"><i class="fas fa-ellipsis-v fa-fw"></i> About</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="https://aner1001.gitee.io/resume/" target="_blank" id="https:aner1001giteeioresume"><i class="fas fa-clock fa-fw"></i> Resume</a></li></ul></li></ul></div><div id="tp-weather-widget"></div><script>!function(e,t,n,a,i,o,c,r){r=function(){o=t.createElement(n),c=t.getElementsByTagName(n)[0],o.src=i,o.charset="utf-8",o.async=1,c.parentNode.insertBefore(o,c)},e.SeniverseWeatherWidgetObject=a,e[a]||(e[a]=function(){(e[a].q=e[a].q||[]).push(arguments)}),e[a].l=+new Date,e.attachEvent?e.attachEvent("onload",r):e.addEventListener("load",r,!1)}(window,document,"script","SeniverseWeatherWidget","//cdn.sencdn.com/widget2/static/js/bundle.js?t="+parseInt(((new Date).getTime()/1e8).toString(),10)),window.SeniverseWeatherWidget("show",{flavor:"slim",location:"WTW3SJ5ZBJUY",geolocation:!0,language:"zh-Hans",unit:"c",theme:"auto",token:"563a4097-8461-469b-ac30-123bac0010d1",hover:"enabled",container:"tp-weather-widget"})</script><div class="m_search"><form name="searchform" class="form u-search-form"><i class="icon fas fa-search fa-fw"></i> <input type="text" class="input u-search-input" placeholder="Search..."></form></div><ul class="switcher nav-list-h m-phone"><li><a class="s-search fas fa-search fa-fw" target="_self" href="javascript:void(0)" rel="external nofollow noreferrer"></a></li><li><a class="s-menu fas fa-bars fa-fw" target="_self" href="javascript:void(0)" rel="external nofollow noreferrer"></a><ul class="menu-phone list-v navigation white-box"><li><a class="menuitem flat-box faa-parent animated-hover" href="/" id="home"><i class="fas fa-home fa-fw"></i> Home</a></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-th-list fa-fw"></i> Articles</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/categories/" id="categories"><i class="fas fa-folder-open fa-fw"></i> Categories</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="/tags/" id="tags"><i class="fas fa-tags fa-fw"></i> Tags</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="/archives/" id="archives"><i class="fas fa-archive fa-fw"></i> Archives</a></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-fan faa-spin animated fa-fw"></i> Play</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/catchTheCat/" id="catchTheCat"><i class="fas fa-cat faa-wrench animated-hover fa-fw"></i> Chat Noir</a></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-cog fa-spin fa-fw"></i> Tools</a><ul class="list-v"><li><a class="menuitem flat-box header toggle-mode-btn"><i class="fas fa-moon fa-fw"></i> 暗黑模式</a></li><li></li></ul></li><li><a class="menuitem flat-box faa-parent animated-hover"><i class="fas fa-info-circle fa-fw"></i> Me</a><ul class="list-v"><li><a class="menuitem flat-box faa-parent animated-hover" href="/about/" id="about"><i class="fas fa-ellipsis-v fa-fw"></i> About</a></li><li><a class="menuitem flat-box faa-parent animated-hover" href="https://aner1001.gitee.io/resume/" target="_blank" id="https:aner1001giteeioresume"><i class="fas fa-clock fa-fw"></i> Resume</a></li></ul></li></ul></li></ul></div></div></div></header><div id="l_body"><div id="l_cover"><div id="full" class="cover-wrapper post blank" style="display:none"><div id="cover-backstretch"></div><div id="scroll-down" style="display:none"><i class="fa fa-chevron-down scroll-down-effects"></i></div></div></div><div id="safearea"><div class="body-wrapper" id="pjax-container"><div class="l_main"><article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost"><div class="article-meta" id="top"><h1 class="title"> Mybatis学习笔记2-映射文件</h1><div class="new-meta-box"><div class="new-meta-item author"> <a class="author" href="/" rel="nofollow"><img no-lazy src="https://yefeit-note-picbed.oss-cn-shanghai.aliyuncs.com/img/cover/fav/cf_1o_x16.jpg"><p>汤晔飞</p></a></div><div class="new-meta-item category"><a class="notlink"><i class="fas fa-folder-open fa-fw" aria-hidden="true"></i> <a class="category-link" href="/categories/%E6%8A%80%E6%9C%AF%E7%9F%A5%E8%AF%86/">技术知识</a><span class="sep"></span><a class="category-link" href="/categories/%E6%8A%80%E6%9C%AF%E7%9F%A5%E8%AF%86/Java/">Java</a></a></div><div class="new-meta-item date"><a class="notlink"><i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i><p>发布于：2021年3月1日</p></a></div><div class="new-meta-item browse leancloud"><a class="notlink"><div id="lc-pv" data-title="Mybatis学习笔记2-映射文件" data-path="/posts/2021/03/01/10b37d7d655c/"><i class="fas fa-eye fa-fw" aria-hidden="true"></i><span id="number"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 次浏览</div></a></div></div></div><p>cache – 该命名空间的缓存配置。<br> cache-ref – 引用其它命名空间的缓存配置。<br> resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。<br> parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。<br> sql – 可被其它语句引用的可重用语句块。<br> insert – 映射插入语句。<br> update – 映射更新语句。<br> delete – 映射删除语句。<br> select – 映射查询语句。</p><span id="more"></span><p>​ 在之前我们学习了mybatis的全局配置文件，下面我们开始学习mybatis的映射文件，在映射文件中，可以编写以下的顶级元素标签：</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">cache – 该命名空间的缓存配置。</span><br><span class="line">cache-ref – 引用其它命名空间的缓存配置。</span><br><span class="line">resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。</span><br><span class="line">parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。</span><br><span class="line">sql – 可被其它语句引用的可重用语句块。</span><br><span class="line">insert – 映射插入语句。</span><br><span class="line">update – 映射更新语句。</span><br><span class="line">delete – 映射删除语句。</span><br><span class="line">select – 映射查询语句。</span><br></pre></td></tr></table></figure><p>​ 在每个顶级元素标签中可以添加很多个属性，下面我们开始详细了解下具体的配置。</p><h2 id="1-insert、update、delete元素"><a class="header-anchor" href="#1-insert、update、delete元素">☀</a>1.insert、update、delete元素</h2><table><thead><tr><th style="text-align:left">属性</th><th style="text-align:left">描述</th></tr></thead><tbody><tr><td style="text-align:left"><code>id</code></td><td style="text-align:left">在命名空间中唯一的标识符，可以被用来引用这条语句。</td></tr><tr><td style="text-align:left"><code>parameterType</code></td><td style="text-align:left">将会传入这条语句的参数的类全限定名或别名。这个属性是可选的，因为 MyBatis 可以通过类型处理器（TypeHandler）推断出具体传入语句的参数，默认值为未设置（unset）。</td></tr><tr><td style="text-align:left"><code>parameterMap</code></td><td style="text-align:left">用于引用外部 parameterMap 的属性，目前已被废弃。请使用行内参数映射和 parameterType 属性。</td></tr><tr><td style="text-align:left"><code>flushCache</code></td><td style="text-align:left">将其设置为 true 后，只要语句被调用，都会导致本地缓存和二级缓存被清空，默认值：（对 insert、update 和 delete 语句）true。</td></tr><tr><td style="text-align:left"><code>timeout</code></td><td style="text-align:left">这个设置是在抛出异常之前，驱动程序等待数据库返回请求结果的秒数。默认值为未设置（unset）（依赖数据库驱动）。</td></tr><tr><td style="text-align:left"><code>statementType</code></td><td style="text-align:left">可选 STATEMENT，PREPARED 或 CALLABLE。这会让 MyBatis 分别使用 Statement，PreparedStatement 或 CallableStatement，默认值：PREPARED。</td></tr><tr><td style="text-align:left"><code>useGeneratedKeys</code></td><td style="text-align:left">（仅适用于 insert 和 update）这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键（比如：像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段），默认值：false。</td></tr><tr><td style="text-align:left"><code>keyProperty</code></td><td style="text-align:left">（仅适用于 insert 和 update）指定能够唯一识别对象的属性，MyBatis 会使用 getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素设置它的值，默认值：未设置（<code>unset</code>）。如果生成列不止一个，可以用逗号分隔多个属性名称。</td></tr><tr><td style="text-align:left"><code>keyColumn</code></td><td style="text-align:left">（仅适用于 insert 和 update）设置生成键值在表中的列名，在某些数据库（像 PostgreSQL）中，当主键列不是表中的第一列的时候，是必须设置的。如果生成列不止一个，可以用逗号分隔多个属性名称。</td></tr><tr><td style="text-align:left"><code>databaseId</code></td><td style="text-align:left">如果配置了数据库厂商标识（databaseIdProvider），MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句；如果带和不带的语句都有，则不带的会被忽略。</td></tr></tbody></table><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--如果数据库支持自增可以使用这样的方式--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insertUser&quot;</span> <span class="attr">useGeneratedKeys</span>=<span class="string">&quot;true&quot;</span> <span class="attr">keyProperty</span>=<span class="string">&quot;id&quot;</span>&gt;</span></span><br><span class="line">       insert into user(user_name) values(#&#123;userName&#125;)</span><br><span class="line">   <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br><span class="line">   <span class="comment">&lt;!--如果数据库不支持自增的话，那么可以使用如下的方式进行赋值查询--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insertUser2&quot;</span> &gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">selectKey</span> <span class="attr">order</span>=<span class="string">&quot;BEFORE&quot;</span> <span class="attr">keyProperty</span>=<span class="string">&quot;id&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;integer&quot;</span>&gt;</span></span><br><span class="line">           select max(id)+1 from user</span><br><span class="line">       <span class="tag">&lt;/<span class="name">selectKey</span>&gt;</span></span><br><span class="line">       insert into user(id,user_name) values(#&#123;id&#125;,#&#123;userName&#125;)</span><br><span class="line">   <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br></pre></td></tr></table></figure><h2 id="2-select元素"><a class="header-anchor" href="#2-select元素">☀</a>2.select元素</h2><h3 id="1-select的参数传递"><a class="header-anchor" href="#1-select的参数传递">☀</a>1.select的参数传递</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">    当查询语句中包含多个参数的是，如果使用#&#123;属性名称&#125;就无法获取具体的值了，那么应该如何使用呢？</span></span><br><span class="line"><span class="comment">        下面就是mybatis的参数传递方式</span></span><br><span class="line"><span class="comment">        1、如果是单个参数，</span></span><br><span class="line"><span class="comment">            基本类型：使用#&#123;随便写&#125;</span></span><br><span class="line"><span class="comment">            引用类型：使用#&#123;类的属性名称&#125;</span></span><br><span class="line"><span class="comment">        2、多个参数：</span></span><br><span class="line"><span class="comment">            当查询的时候传入多个参数的时候，就无法简单的通过#&#123;参数名&#125;来获取值了，</span></span><br><span class="line"><span class="comment">            只能通过arg0,arg1...或者param1,param2等方式来获取值</span></span><br><span class="line"><span class="comment">            原因就在于，mybatis在传入多个参数的时候，会将这些参数封装到一个map中，此时map中的key就是</span></span><br><span class="line"><span class="comment">            arg0,arg1,param1,param2这些值，但是很明显，这样的传值方式不是很友好，没有办法根据参数的名称来</span></span><br><span class="line"><span class="comment">            获取具体的值，因此可以使用如下的方式来指定参数的key是什么</span></span><br><span class="line"><span class="comment">            Emp selectEmpByNoAndName(@Param(&quot;empno&quot;) Integer empno, @Param(&quot;ename&quot;) String ename);</span></span><br><span class="line"><span class="comment">                也就是通过@Param来指定存入map中的key值是什么</span></span><br><span class="line"><span class="comment">        3、使用map来传递参数：</span></span><br><span class="line"><span class="comment">                依然是直接使用#&#123;key&#125;来获取具体的属性值</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpByNoAndName&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where empno=#&#123;empno&#125; and ename=#&#123;ename&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpByNoAndName2&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where empno=#&#123;empno&#125; and ename=#&#123;ename&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="2-参数的取值方式"><a class="header-anchor" href="#2-参数的取值方式">☀</a>2.参数的取值方式</h3><p>​ 在xml文件中编写sql语句的时候有两种取值的方式，分别是#{}和${}，下面来看一下他们之间的区别：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">       当使用#&#123;&#125;来获取值的时候会发现打印的sql语句如下：</span></span><br><span class="line"><span class="comment">           select * from emp where empno=? and ename=?</span></span><br><span class="line"><span class="comment">       当使用$&#123;&#125;来获取值的时候会发现打印的sql语句如下：</span></span><br><span class="line"><span class="comment">           select * from emp where empno=7369 and ename=&#x27;SMITH&#x27;</span></span><br><span class="line"><span class="comment">       通过刚刚的案例大家已经发现了存在的问题了，</span></span><br><span class="line"><span class="comment">       使用#&#123;&#125;方式进行取值：采用的是参数预编译的方式，参数的位置使用？进行替代，不会出现sql注入的问题</span></span><br><span class="line"><span class="comment">       使用$&#123;&#125;方式进行取值：采用的是直接跟sql语句进行拼接的方式</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">	此处大家需要注意，如果我们的sql语句中的某些值不支持参数预编译，那么就必须要使用$&#123;&#125;的方式来取值了</span></span><br><span class="line"><span class="comment">   --&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpByNoAndName&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">       select * from #&#123;t&#125; where empno=$&#123;empno&#125; and ename=$&#123;ename&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="3-处理集合返回结果"><a class="header-anchor" href="#3-处理集合返回结果">☀</a>3.处理集合返回结果</h3><p>EmpDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--当返回值的结果是集合的时候，返回值的类型依然写的是集合中具体的类型--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectAllEmp&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select  * from emp</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--在查询的时候可以设置返回值的类型为map，当mybatis查询完成之后会把列的名称作为key</span></span><br><span class="line"><span class="comment">    列的值作为value，转换到map中</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpByEmpReturnMap&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;map&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where empno = #&#123;empno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--注意，当返回的结果是一个集合对象的是，返回值的类型一定要写集合具体value的类型</span></span><br><span class="line"><span class="comment">    同时在dao的方法上要添加@MapKey的注解，来设置key是什么结果</span></span><br><span class="line"><span class="comment">    @MapKey(&quot;empno&quot;)</span></span><br><span class="line"><span class="comment">    Map&lt;Integer,Emp&gt; getAllEmpReturnMap();--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getAllEmpReturnMap&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><p>UserDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.MapKey;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Param;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">EmpDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Emp <span class="title function_">findEmpByEmpno</span><span class="params">(Integer empno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">updateEmp</span><span class="params">(Emp emp)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">deleteEmp</span><span class="params">(Integer empno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">insertEmp</span><span class="params">(Emp emp)</span>;</span><br><span class="line"></span><br><span class="line">    Emp <span class="title function_">selectEmpByNoAndName</span><span class="params">(<span class="meta">@Param(&quot;empno&quot;)</span> Integer empno, <span class="meta">@Param(&quot;ename&quot;)</span> String ename,<span class="meta">@Param(&quot;t&quot;)</span> String tablename)</span>;</span><br><span class="line">    Emp <span class="title function_">selectEmpByNoAndName2</span><span class="params">(Map&lt;String,Object&gt; map)</span>;</span><br><span class="line"></span><br><span class="line">    List&lt;Emp&gt; <span class="title function_">selectAllEmp</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    Map&lt;String,Object&gt; <span class="title function_">selectEmpByEmpReturnMap</span><span class="params">(Integer empno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MapKey(&quot;empno&quot;)</span></span><br><span class="line">    Map&lt;Integer,Emp&gt; <span class="title function_">getAllEmpReturnMap</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="4-自定义结果集—resultMap"><a class="header-anchor" href="#4-自定义结果集—resultMap">☀</a>4.自定义结果集—resultMap</h3><p>Dog.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dog</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String gender;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setId</span><span class="params">(Integer id)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setName</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getAge</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setAge</span><span class="params">(Integer age)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getGender</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> gender;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setGender</span><span class="params">(String gender)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.gender = gender;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Dog&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;id=&quot;</span> + id +</span><br><span class="line">                <span class="string">&quot;, name=&#x27;&quot;</span> + name + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, age=&quot;</span> + age +</span><br><span class="line">                <span class="string">&quot;, gender=&#x27;&quot;</span> + gender + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>dog.sql</p><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">Navicat MySQL Data Transfer</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">Source Server         : node01</span></span><br><span class="line"><span class="comment">Source Server Version : 50729</span></span><br><span class="line"><span class="comment">Source Host           : 192.168.85.111:3306</span></span><br><span class="line"><span class="comment">Source Database       : demo</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">Target Server Type    : MYSQL</span></span><br><span class="line"><span class="comment">Target Server Version : 50729</span></span><br><span class="line"><span class="comment">File Encoding         : 65001</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">Date: 2020-03-24 23:54:22</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">SET</span> FOREIGN_KEY_CHECKS<span class="operator">=</span><span class="number">0</span>;</span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="comment">-- Table structure for `dog`</span></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> IF <span class="keyword">EXISTS</span> `dog`;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `dog` (</span><br><span class="line">  `id` <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  `dname` <span class="type">varchar</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `dage` <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `dgender` <span class="type">varchar</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY (`id`)</span><br><span class="line">) ENGINE<span class="operator">=</span>InnoDB AUTO_INCREMENT<span class="operator">=</span><span class="number">4</span> <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8;</span><br><span class="line"></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="comment">-- Records of dog</span></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> dog <span class="keyword">VALUES</span> (<span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;大黄&#x27;</span>, <span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;雄&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> dog <span class="keyword">VALUES</span> (<span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;二黄&#x27;</span>, <span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;雌&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> dog <span class="keyword">VALUES</span> (<span class="string">&#x27;3&#x27;</span>, <span class="string">&#x27;三黄&#x27;</span>, <span class="string">&#x27;3&#x27;</span>, <span class="string">&#x27;雄&#x27;</span>);</span><br></pre></td></tr></table></figure><p>DogDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Dog;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DogDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dog <span class="title function_">selectDogById</span><span class="params">(Integer id)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>DogDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.DogDao&quot;</span>&gt;</span></span><br><span class="line">   <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">   在使用mybatis进行查询的时候，mybatis默认会帮我们进行结果的封装，但是要求列名跟属性名称一一对应上</span></span><br><span class="line"><span class="comment">   在实际的使用过程中，我们会发现有时候数据库中的列名跟我们类中的属性名并不是一一对应的，此时就需要起别名</span></span><br><span class="line"><span class="comment">   起别名有两种实现方式：</span></span><br><span class="line"><span class="comment">      1、在编写sql语句的时候添加别名</span></span><br><span class="line"><span class="comment">      2、自定义封装结果集</span></span><br><span class="line"><span class="comment">   --&gt;</span></span><br><span class="line">   <span class="comment">&lt;!--根据查询的数据进行结果的封装要使用resultMap属性，表示使用自定义规则--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectDogById&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;myDog&quot;</span>&gt;</span></span><br><span class="line">      select * from dog where id = #&#123;id&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">&lt;!--自定义结果集，将每一个列的数据跟javaBean的对象属性对应起来</span></span><br><span class="line"><span class="comment">   type:表示为哪一个javaBean对象进行对应</span></span><br><span class="line"><span class="comment">   id:唯一标识，方便其他属性标签进行引用</span></span><br><span class="line"><span class="comment">   --&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;myDog&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Dog&quot;</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">      指定主键列的对应规则：</span></span><br><span class="line"><span class="comment">      column：表示表中的主键列</span></span><br><span class="line"><span class="comment">      property:指定javaBean的属性</span></span><br><span class="line"><span class="comment">      --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--设置其他列的对应关系--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;dname&quot;</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;dage&quot;</span> <span class="attr">property</span>=<span class="string">&quot;age&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;dgender&quot;</span> <span class="attr">property</span>=<span class="string">&quot;gender&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line">   <span class="comment">&lt;!--可以在sql语句中写别名--&gt;</span></span><br><span class="line"> <span class="comment">&lt;!--  &lt;select id=&quot;selectDogById&quot; resultType=&quot;com.mashibing.bean.Dog&quot;&gt;</span></span><br><span class="line"><span class="comment">      select id id,dname name,dage age,dgender gender from dog where id = #&#123;id&#125;</span></span><br><span class="line"><span class="comment">   &lt;/select&gt;--&gt;</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">&lt;!--这种方式是查询不到任何结果的，因为属性名跟列名并不是一一对应的--&gt;</span></span><br><span class="line">  <span class="comment">&lt;!-- &lt;select id=&quot;selectDogById&quot; resultType=&quot;com.mashibing.bean.Dog&quot;&gt;</span></span><br><span class="line"><span class="comment">      select * from dog where id = #&#123;id&#125;</span></span><br><span class="line"><span class="comment">   &lt;/select&gt;--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="5-联合查询"><a class="header-anchor" href="#5-联合查询">☀</a>5.联合查询</h3><p>emp.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Emp</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Integer empno;</span><br><span class="line">    <span class="keyword">private</span> String ename;</span><br><span class="line">    <span class="keyword">private</span> String job;</span><br><span class="line">    <span class="keyword">private</span> Integer mgr;</span><br><span class="line">    <span class="keyword">private</span> Date hiredate;</span><br><span class="line">    <span class="keyword">private</span> Double sal;</span><br><span class="line">    <span class="keyword">private</span> Double common;</span><br><span class="line">    <span class="keyword">private</span> Dept dept;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Emp</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Emp</span><span class="params">(Integer empno, String ename)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.empno = empno;</span><br><span class="line">        <span class="built_in">this</span>.ename = ename;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Emp</span><span class="params">(Integer empno, String ename, String job, Integer mgr, Date hiredate, Double sal, Double common, Dept dept)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.empno = empno;</span><br><span class="line">        <span class="built_in">this</span>.ename = ename;</span><br><span class="line">        <span class="built_in">this</span>.job = job;</span><br><span class="line">        <span class="built_in">this</span>.mgr = mgr;</span><br><span class="line">        <span class="built_in">this</span>.hiredate = hiredate;</span><br><span class="line">        <span class="built_in">this</span>.sal = sal;</span><br><span class="line">        <span class="built_in">this</span>.common = common;</span><br><span class="line">        <span class="built_in">this</span>.dept = dept;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getEmpno</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> empno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setEmpno</span><span class="params">(Integer empno)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.empno = empno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getEname</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> ename;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setEname</span><span class="params">(String ename)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.ename = ename;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getJob</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> job;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setJob</span><span class="params">(String job)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.job = job;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getMgr</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> mgr;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setMgr</span><span class="params">(Integer mgr)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.mgr = mgr;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Date <span class="title function_">getHiredate</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> hiredate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setHiredate</span><span class="params">(Date hiredate)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.hiredate = hiredate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Double <span class="title function_">getSal</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> sal;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setSal</span><span class="params">(Double sal)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.sal = sal;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Double <span class="title function_">getCommon</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> common;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setCommon</span><span class="params">(Double common)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.common = common;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDept</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> dept;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDept</span><span class="params">(Dept dept)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.dept = dept;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Emp&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;empno=&quot;</span> + empno +</span><br><span class="line">                <span class="string">&quot;, ename=&#x27;&quot;</span> + ename + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, job=&#x27;&quot;</span> + job + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, mgr=&quot;</span> + mgr +</span><br><span class="line">                <span class="string">&quot;, hiredate=&quot;</span> + hiredate +</span><br><span class="line">                <span class="string">&quot;, sal=&quot;</span> + sal +</span><br><span class="line">                <span class="string">&quot;, common=&quot;</span> + common +</span><br><span class="line">                <span class="string">&quot;, dept=&quot;</span> + dept +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>Dept.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dept</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer deptno;</span><br><span class="line">    <span class="keyword">private</span> String dname;</span><br><span class="line">    <span class="keyword">private</span> String loc;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Dept</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Dept</span><span class="params">(Integer deptno, String dname, String loc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.deptno = deptno;</span><br><span class="line">        <span class="built_in">this</span>.dname = dname;</span><br><span class="line">        <span class="built_in">this</span>.loc = loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getDeptno</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> deptno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDeptno</span><span class="params">(Integer deptno)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.deptno = deptno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDname</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> dname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDname</span><span class="params">(String dname)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.dname = dname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getLoc</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setLoc</span><span class="params">(String loc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.loc = loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Dept&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;deptno=&quot;</span> + deptno +</span><br><span class="line">                <span class="string">&quot;, dname=&#x27;&quot;</span> + dname + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, loc=&#x27;&quot;</span> + loc + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>EmpDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--namespace:编写接口的全类名，就是告诉要实现该配置文件是哪个接口的具体实现--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.EmpDao&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--再做查询的时候，有时候需要关联其他对象，因此需要使用关联查询</span></span><br><span class="line"><span class="comment">    可以通过下面自定义结果集的方式实现</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpAndDept&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;empDept&quot;</span>&gt;</span></span><br><span class="line">        select * from emp left join dept on emp.deptno = dept.deptno where empno = #&#123;empno&#125;;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;empDept&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;empno&quot;</span> <span class="attr">property</span>=<span class="string">&quot;empno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;ename&quot;</span> <span class="attr">property</span>=<span class="string">&quot;ename&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;job&quot;</span> <span class="attr">property</span>=<span class="string">&quot;job&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;mgr&quot;</span> <span class="attr">property</span>=<span class="string">&quot;mgr&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;hiredate&quot;</span> <span class="attr">property</span>=<span class="string">&quot;hiredate&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;sal&quot;</span> <span class="attr">property</span>=<span class="string">&quot;sal&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;comm&quot;</span> <span class="attr">property</span>=<span class="string">&quot;common&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">property</span>=<span class="string">&quot;dept.deptno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;dname&quot;</span> <span class="attr">property</span>=<span class="string">&quot;dept.dname&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;loc&quot;</span> <span class="attr">property</span>=<span class="string">&quot;dept.loc&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--在mybatis中还提供了一种简单的形式，使用association标签可以搞定</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;empDept&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;empno&quot;</span> <span class="attr">property</span>=<span class="string">&quot;empno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;ename&quot;</span> <span class="attr">property</span>=<span class="string">&quot;ename&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;job&quot;</span> <span class="attr">property</span>=<span class="string">&quot;job&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;mgr&quot;</span> <span class="attr">property</span>=<span class="string">&quot;mgr&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;hiredate&quot;</span> <span class="attr">property</span>=<span class="string">&quot;hiredate&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;sal&quot;</span> <span class="attr">property</span>=<span class="string">&quot;sal&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;comm&quot;</span> <span class="attr">property</span>=<span class="string">&quot;common&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;dept&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;com.mashibing.bean.Dept&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">property</span>=<span class="string">&quot;deptno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;dname&quot;</span> <span class="attr">property</span>=<span class="string">&quot;dname&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;loc&quot;</span> <span class="attr">property</span>=<span class="string">&quot;loc&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">association</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>Test</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test08</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取数据库的会话</span></span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">        <span class="type">Emp</span> <span class="variable">emp</span> <span class="operator">=</span> mapper.selectEmpAndDept(<span class="number">7369</span>);</span><br><span class="line">        System.out.println(emp);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        sqlSession.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="6-获取集合元素"><a class="header-anchor" href="#6-获取集合元素">☀</a>6.获取集合元素</h3><p>Dept.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Dept</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer deptno;</span><br><span class="line">    <span class="keyword">private</span> String dname;</span><br><span class="line">    <span class="keyword">private</span> String loc;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List&lt;Emp&gt; emps;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Dept</span><span class="params">()</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Dept</span><span class="params">(Integer deptno, String dname, String loc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.deptno = deptno;</span><br><span class="line">        <span class="built_in">this</span>.dname = dname;</span><br><span class="line">        <span class="built_in">this</span>.loc = loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getDeptno</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> deptno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDeptno</span><span class="params">(Integer deptno)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.deptno = deptno;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getDname</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> dname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setDname</span><span class="params">(String dname)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.dname = dname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getLoc</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setLoc</span><span class="params">(String loc)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.loc = loc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> List&lt;Emp&gt; <span class="title function_">getEmps</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> emps;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setEmps</span><span class="params">(List&lt;Emp&gt; emps)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.emps = emps;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Dept&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;deptno=&quot;</span> + deptno +</span><br><span class="line">                <span class="string">&quot;, dname=&#x27;&quot;</span> + dname + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, loc=&#x27;&quot;</span> + loc + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, emps=&quot;</span> + emps +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>DeptDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Dept;</span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DeptDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmps</span><span class="params">(Integer deptno)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>DeptDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.DeptDao&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义查询集合元素--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getDeptAndEmps&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;deptEmp&quot;</span>&gt;</span></span><br><span class="line">        select * from dept left join emp on dept.deptno = emp.deptno where dept.deptno=#&#123;deptno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;deptEmp&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Dept&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;dname&quot;</span> <span class="attr">column</span>=<span class="string">&quot;dname&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;loc&quot;</span> <span class="attr">column</span>=<span class="string">&quot;loc&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--封装集合类的元素</span></span><br><span class="line"><span class="comment">            property：指定集合的属性</span></span><br><span class="line"><span class="comment">            ofType:指定集合中的元素类型</span></span><br><span class="line"><span class="comment">        --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">&quot;emps&quot;</span> <span class="attr">ofType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;empno&quot;</span> <span class="attr">column</span>=<span class="string">&quot;empno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;ename&quot;</span> <span class="attr">property</span>=<span class="string">&quot;ename&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;job&quot;</span> <span class="attr">property</span>=<span class="string">&quot;job&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;mgr&quot;</span> <span class="attr">property</span>=<span class="string">&quot;mgr&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;hiredate&quot;</span> <span class="attr">property</span>=<span class="string">&quot;hiredate&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;sal&quot;</span> <span class="attr">property</span>=<span class="string">&quot;sal&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;comm&quot;</span> <span class="attr">property</span>=<span class="string">&quot;common&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">collection</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>Test</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test09</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取数据库的会话</span></span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">DeptDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(DeptDao.class);</span><br><span class="line">        <span class="type">Dept</span> <span class="variable">deptAndEmps</span> <span class="operator">=</span> mapper.getDeptAndEmps(<span class="number">10</span>);</span><br><span class="line">        System.out.println(deptAndEmps);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        sqlSession.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="7-分步查询"><a class="header-anchor" href="#7-分步查询">☀</a>7.分步查询</h3><p>​ 在上述逻辑的查询中，是由我们自己来完成sql语句的关联查询的，那么，我们能让mybatis帮我们实现自动的关联查询吗?</p><p><strong>关联查询的分步</strong></p><p>DeptDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Dept;</span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DeptDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmps</span><span class="params">(Integer deptno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmpsBySimple</span><span class="params">(Integer deptno)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>EmpDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.MapKey;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Param;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">EmpDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    Emp <span class="title function_">selectEmpAndDept</span><span class="params">(Integer empno)</span>;</span><br><span class="line">    Emp <span class="title function_">selectEmpAndDeptBySimple</span><span class="params">(Integer empno)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>DeptDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.DeptDao&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getDeptAndEmpsBySimple&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Dept&quot;</span>&gt;</span></span><br><span class="line">        select * from dept where deptno = #&#123;deptno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>EmpDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.EmpDao&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpAndDeptBySimple&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;simpleEmpAndDept&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where empno = #&#123;empno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;simpleEmpAndDept&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;empno&quot;</span> <span class="attr">property</span>=<span class="string">&quot;empno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;ename&quot;</span> <span class="attr">property</span>=<span class="string">&quot;ename&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;job&quot;</span> <span class="attr">property</span>=<span class="string">&quot;job&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;mgr&quot;</span> <span class="attr">property</span>=<span class="string">&quot;mgr&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;hiredate&quot;</span> <span class="attr">property</span>=<span class="string">&quot;hiredate&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;sal&quot;</span> <span class="attr">property</span>=<span class="string">&quot;sal&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;comm&quot;</span> <span class="attr">property</span>=<span class="string">&quot;common&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;dept&quot;</span> <span class="attr">select</span>=<span class="string">&quot;com.mashibing.dao.DeptDao.getDeptAndEmpsBySimple&quot;</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">association</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>Test</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test08</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取数据库的会话</span></span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line"><span class="comment">//            Emp emp = mapper.selectEmpAndDept(7369);</span></span><br><span class="line">            <span class="type">Emp</span> <span class="variable">emp</span> <span class="operator">=</span> mapper.selectEmpAndDeptBySimple(<span class="number">7369</span>);</span><br><span class="line">            System.out.println(emp);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            sqlSession.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure><p><strong>集合的分步查询</strong></p><p>EmpDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.MapKey;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Param;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">EmpDao</span> &#123;</span><br><span class="line">    Emp <span class="title function_">selectEmpAndDeptBySimple</span><span class="params">(Integer empno)</span>;</span><br><span class="line">    Emp <span class="title function_">selectEmpByStep</span><span class="params">(Integer empno)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>DeptDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mashibing.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Dept;</span><br><span class="line"><span class="keyword">import</span> com.mashibing.bean.Emp;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">DeptDao</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmps</span><span class="params">(Integer deptno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmpsBySimple</span><span class="params">(Integer deptno)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Dept <span class="title function_">getDeptAndEmpsByStep</span><span class="params">(Integer deptno)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>EmpDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.EmpDao&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectEmpByStep&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where deptno = #&#123;deptno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>DeptDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mashibing.dao.DeptDao&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getDeptAndEmpsByStep&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;deptEmpByStep&quot;</span>&gt;</span></span><br><span class="line">        select * from dept where deptno = #&#123;deptno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;deptEmpByStep&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.mashibing.bean.Dept&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;dname&quot;</span> <span class="attr">column</span>=<span class="string">&quot;dname&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;loc&quot;</span> <span class="attr">column</span>=<span class="string">&quot;loc&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">result</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--封装集合类的元素</span></span><br><span class="line"><span class="comment">            property：指定集合的属性</span></span><br><span class="line"><span class="comment">            ofType:指定集合中的元素类型</span></span><br><span class="line"><span class="comment">        --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">&quot;emps&quot;</span> <span class="attr">ofType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span> <span class="attr">select</span>=<span class="string">&quot;com.mashibing.dao.EmpDao.selectEmpByStep&quot;</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">collection</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure><p>Test</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test09</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取数据库的会话</span></span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">DeptDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(DeptDao.class);</span><br><span class="line"><span class="comment">//            Dept deptAndEmps = mapper.getDeptAndEmps(10);</span></span><br><span class="line">            <span class="type">Dept</span> <span class="variable">deptAndEmpsByStep</span> <span class="operator">=</span> mapper.getDeptAndEmpsByStep(<span class="number">10</span>);</span><br><span class="line">            System.out.println(deptAndEmpsByStep);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            sqlSession.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure><h3 id="8-延迟查询"><a class="header-anchor" href="#8-延迟查询">☀</a>8.延迟查询</h3><p>​ 当我们在进行表关联的时候，有可能在查询结果的时候不需要关联对象的属性值，那么此时可以通过延迟加载来实现功能。在全局配置文件中添加如下属性</p><p>mybatis-config.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">settings</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--开启延时加载--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;lazyLoadingEnabled&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">settings</span>&gt;</span></span><br></pre></td></tr></table></figure><p>如果设置了全局加载，但是希望在某一个sql语句查询的时候不适用延时策略，可以添加如下属性：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;dept&quot;</span> <span class="attr">select</span>=<span class="string">&quot;com.mashibing.dao.DeptDao.getDeptAndEmpsBySimple&quot;</span> <span class="attr">column</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">fetchType</span>=<span class="string">&quot;eager&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure><h2 id="3-动态sql"><a class="header-anchor" href="#3-动态sql">☀</a>3.动态sql</h2><p>​ 动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架，你应该能理解根据不同条件拼接 SQL 语句有多痛苦，例如拼接时要确保不能忘记添加必要的空格，还要注意去掉列表最后一个列名的逗号。利用动态 SQL，可以彻底摆脱这种痛苦。</p><p>​ 使用动态 SQL 并非一件易事，但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言，MyBatis 显著地提升了这一特性的易用性。</p><p>​ 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器，你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中，需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式，MyBatis 3 替换了之前的大部分元素，大大精简了元素种类，现在要学习的元素种类比原来的一半还要少。</p><ul><li>if</li><li>choose (when, otherwise)</li><li>trim (where, set)</li><li>foreach</li></ul><h3 id="1-if"><a class="header-anchor" href="#1-if">☀</a>1.if</h3><p>EmpDao.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getEmpByCondition&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where</span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;empno!=null&quot;</span>&gt;</span></span><br><span class="line">            empno &gt; #&#123;empno&#125; and</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;ename!=null&quot;</span>&gt;</span></span><br><span class="line">            ename like #&#123;ename&#125; and</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;sal!=null&quot;</span>&gt;</span></span><br><span class="line">            sal &gt; #&#123;sal&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><p>EmpDao.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;Emp&gt; <span class="title function_">getEmpByCondition</span><span class="params">(Emp emp)</span>;</span><br></pre></td></tr></table></figure><p>Test.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test10</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">           <span class="type">Emp</span> <span class="variable">emp</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Emp</span>();</span><br><span class="line">           emp.setEmpno(<span class="number">6500</span>);</span><br><span class="line">           emp.setEname(<span class="string">&quot;%E%&quot;</span>);</span><br><span class="line">           emp.setSal(<span class="number">500.0</span>);</span><br><span class="line">           List&lt;Emp&gt; empByCondition = mapper.getEmpByCondition(emp);</span><br><span class="line">           <span class="keyword">for</span> (Emp emp1 : empByCondition) &#123;</span><br><span class="line">               System.out.println(emp1);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           sqlSession.close();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>​ 看起来测试是比较正常的，但是大家需要注意的是如果我们传入的参数值有缺失会怎么呢？这个时候拼接的sql语句就会变得有问题，例如不传参数或者丢失最后一个参数，那么语句中就会多一个where或者and的关键字，因此在mybatis中也给出了具体的解决方案：</p><p>​ <em>where</em> 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且，若子句的开头为 “AND” 或 “OR”，<em>where</em> 元素也会将它们去除。</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getEmpByCondition&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp</span><br><span class="line">        <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;empno!=null&quot;</span>&gt;</span></span><br><span class="line">                empno &gt; #&#123;empno&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;ename!=null&quot;</span>&gt;</span></span><br><span class="line">                and ename like #&#123;ename&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;sal!=null&quot;</span>&gt;</span></span><br><span class="line">                and sal &gt; #&#123;sal&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><p>​ 现在看起来没有什么问题了，但是我们的条件添加到了拼接sql语句的前后，那么我们该如何处理呢？</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">   trim截取字符串：</span></span><br><span class="line"><span class="comment">   prefix：前缀，为sql整体添加一个前缀</span></span><br><span class="line"><span class="comment">   prefixOverrides:去除整体字符串前面多余的字符</span></span><br><span class="line"><span class="comment">   suffixOverrides:去除后面多余的字符串</span></span><br><span class="line"><span class="comment">   --&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getEmpByCondition&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">       select * from emp</span><br><span class="line"></span><br><span class="line">       <span class="tag">&lt;<span class="name">trim</span> <span class="attr">prefix</span>=<span class="string">&quot;where&quot;</span> <span class="attr">prefixOverrides</span>=<span class="string">&quot;and&quot;</span> <span class="attr">suffixOverrides</span>=<span class="string">&quot;and&quot;</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;empno!=null&quot;</span>&gt;</span></span><br><span class="line">               empno &gt; #&#123;empno&#125; and</span><br><span class="line">           <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;ename!=null&quot;</span>&gt;</span></span><br><span class="line">               ename like #&#123;ename&#125; and</span><br><span class="line">           <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;sal!=null&quot;</span>&gt;</span></span><br><span class="line">               sal &gt; #&#123;sal&#125; and</span><br><span class="line">           <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">trim</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="2-foreach"><a class="header-anchor" href="#2-foreach">☀</a>2.foreach</h3><p>​ 动态 SQL 的另一个常见使用场景是对集合进行遍历（尤其是在构建 IN 条件语句的时候）。</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--foreach是对集合进行遍历</span></span><br><span class="line"><span class="comment">    collection=&quot;deptnos&quot;  指定要遍历的集合</span></span><br><span class="line"><span class="comment">    close=&quot;&quot; 表示以什么结束</span></span><br><span class="line"><span class="comment">    index=&quot;&quot; 给定一个索引值</span></span><br><span class="line"><span class="comment">    item=&quot;&quot;  遍历的每一个元素的值</span></span><br><span class="line"><span class="comment">    open=&quot;&quot;  表示以什么开始</span></span><br><span class="line"><span class="comment">    separator=&quot;&quot; 表示多个元素的分隔符</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getEmpByDeptnos&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp where deptno in</span><br><span class="line">        <span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;deptnos&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">index</span>=<span class="string">&quot;idx&quot;</span> <span class="attr">item</span>=<span class="string">&quot;deptno&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">            #&#123;deptno&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="3-choose"><a class="header-anchor" href="#3-choose">☀</a>3.choose</h3><p>​ 有时候，我们不想使用所有的条件，而只是想从多个条件中选择一个使用。针对这种情况，MyBatis 提供了 choose 元素，它有点像 Java 中的 switch 语句。</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getEmpByConditionChoose&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mashibing.bean.Emp&quot;</span>&gt;</span></span><br><span class="line">        select * from emp</span><br><span class="line">        <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">choose</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;empno!=null&quot;</span>&gt;</span></span><br><span class="line">                    empno &gt; #&#123;empno&#125;</span><br><span class="line">                <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;ename!=null&quot;</span>&gt;</span></span><br><span class="line">                    ename like #&#123;ename&#125;</span><br><span class="line">                <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;sal!=null&quot;</span>&gt;</span></span><br><span class="line">                    sal &gt; #&#123;sal&#125;</span><br><span class="line">                <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></span><br><span class="line">                    1=1</span><br><span class="line">                <span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">choose</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure><h3 id="4-set"><a class="header-anchor" href="#4-set">☀</a>4.set</h3><p>​ 用于动态更新语句的类似解决方案叫做 <em>set</em>。<em>set</em> 元素可以用于动态包含需要更新的列，忽略其它不更新的列。</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateEmpByEmpno&quot;</span>&gt;</span></span><br><span class="line">    update emp</span><br><span class="line">    <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;empno!=null&quot;</span>&gt;</span></span><br><span class="line">            empno=#&#123;empno&#125;,</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;ename!=null&quot;</span>&gt;</span></span><br><span class="line">            ename = #&#123;ename&#125;,</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;sal!=null&quot;</span>&gt;</span></span><br><span class="line">            sal = #&#123;sal&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">        empno = #&#123;empno&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure><h2 id="4-缓存"><a class="header-anchor" href="#4-缓存">☀</a>4.缓存</h2><p>​ MyBatis 内置了一个强大的事务性查询缓存机制，它可以非常方便地配置和定制。 为了使它更加强大而且易于配置，我们对 MyBatis 3 中的缓存实现进行了许多改进。</p><p>​ 默认情况下，只启用了本地的会话缓存，它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存，只需要在你的 SQL 映射文件中添加一行：</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;cache/&gt;</span><br></pre></td></tr></table></figure><p>当添加上该标签之后，会有如下效果：</p><ul><li>映射语句文件中的所有 select 语句的结果将会被缓存。</li><li>映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。</li><li>缓存会使用最近最少使用算法（LRU, Least Recently Used）算法来清除不需要的缓存。</li><li>缓存不会定时进行刷新（也就是说，没有刷新间隔）。</li><li>缓存会保存列表或对象（无论查询方法返回哪种）的 1024 个引用。</li><li>缓存会被视为读/写缓存，这意味着获取到的对象并不是共享的，可以安全地被调用者修改，而不干扰其他调用者或线程所做的潜在修改。</li></ul><p>在进行配置的时候还会分为一级缓存和二级缓存：</p><p>一级缓存：线程级别的缓存，是本地缓存，sqlSession级别的缓存</p><p>二级缓存：全局范围的缓存，不止局限于当前会话</p><h3 id="1-一级缓存的使用"><a class="header-anchor" href="#1-一级缓存的使用">☀</a>1.一级缓存的使用</h3><p>​ 一级缓存是sqlsession级别的缓存，默认是存在的。在下面的案例中，大家发现我发送了两个相同的请求，但是sql语句仅仅执行了一次，那么就意味着第一次查询的时候已经将结果进行了缓存。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test01</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">           List&lt;Emp&gt; list = mapper.selectAllEmp();</span><br><span class="line">           <span class="keyword">for</span> (Emp emp : list) &#123;</span><br><span class="line">               System.out.println(emp);</span><br><span class="line">           &#125;</span><br><span class="line">           System.out.println(<span class="string">&quot;--------------------------------&quot;</span>);</span><br><span class="line">           List&lt;Emp&gt; list2 = mapper.selectAllEmp();</span><br><span class="line">           <span class="keyword">for</span> (Emp emp : list2) &#123;</span><br><span class="line">               System.out.println(emp);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           sqlSession.close();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><p>​ 在大部分的情况下一级缓存是可以的，但是有几种特殊的情况会造成一级缓存失效：</p><p>1、一级缓存是sqlSession级别的缓存，如果在应用程序中只有开启了多个sqlsession，那么会造成缓存失效</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test02</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">        <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">        List&lt;Emp&gt; list = mapper.selectAllEmp();</span><br><span class="line">        <span class="keyword">for</span> (Emp emp : list) &#123;</span><br><span class="line">            System.out.println(emp);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;================================&quot;</span>);</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession2</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">        <span class="type">EmpDao</span> <span class="variable">mapper2</span> <span class="operator">=</span> sqlSession2.getMapper(EmpDao.class);</span><br><span class="line">        List&lt;Emp&gt; list2 = mapper2.selectAllEmp();</span><br><span class="line">        <span class="keyword">for</span> (Emp emp : list2) &#123;</span><br><span class="line">            System.out.println(emp);</span><br><span class="line">        &#125;</span><br><span class="line">        sqlSession.close();</span><br><span class="line">        sqlSession2.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure><p>2、在编写查询的sql语句的时候，一定要注意传递的参数，如果参数不一致，那么也不会缓存结果</p><p>3、如果在发送过程中发生了数据的修改，那么结果就不会缓存</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test03</span><span class="params">()</span>&#123;</span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno);</span><br><span class="line">       System.out.println(<span class="string">&quot;================================&quot;</span>);</span><br><span class="line">       empByEmpno.setEname(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">       <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> mapper.updateEmp(empByEmpno);</span><br><span class="line">       System.out.println(i);</span><br><span class="line">       System.out.println(<span class="string">&quot;================================&quot;</span>);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno1</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno1);</span><br><span class="line">       sqlSession.close();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>4、在两次查询期间，手动去清空缓存，也会让缓存失效</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test03</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">        <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">        <span class="type">Emp</span> <span class="variable">empByEmpno</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">        System.out.println(empByEmpno);</span><br><span class="line">        System.out.println(<span class="string">&quot;================================&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;手动清空缓存&quot;</span>);</span><br><span class="line">        sqlSession.clearCache();</span><br><span class="line">        System.out.println(<span class="string">&quot;================================&quot;</span>);</span><br><span class="line">        <span class="type">Emp</span> <span class="variable">empByEmpno1</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">        System.out.println(empByEmpno1);</span><br><span class="line">        sqlSession.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure><h3 id="2-二级缓存"><a class="header-anchor" href="#2-二级缓存">☀</a>2.二级缓存</h3><p>​ 二级缓存是全局作用域缓存，默认是不开启的，需要手动进行配置。</p><p>​ Mybatis提供二级缓存的接口以及实现，缓存实现的时候要求实体类实现Serializable接口，二级缓存在sqlSession关闭或提交之后才会生效。</p><h4 id="1-缓存的使用"><a class="header-anchor" href="#1-缓存的使用">☀</a>1.缓存的使用</h4><p>​ 步骤：</p><p>​ 1、全局配置文件中添加如下配置：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;cacheEnabled&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure><p>​ 2、需要在使用二级缓存的映射文件出使用<cache>标签标注</p><p>​ 3、实体类必须要实现Serializable接口</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test04</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession2</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">    <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">    <span class="type">EmpDao</span> <span class="variable">mapper2</span> <span class="operator">=</span> sqlSession2.getMapper(EmpDao.class);</span><br><span class="line">    <span class="type">Emp</span> <span class="variable">empByEmpno</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">    System.out.println(empByEmpno);</span><br><span class="line">    sqlSession.close();</span><br><span class="line"></span><br><span class="line">    <span class="type">Emp</span> <span class="variable">empByEmpno1</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">    System.out.println(empByEmpno1);</span><br><span class="line">    sqlSession2.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="2-缓存的属性"><a class="header-anchor" href="#2-缓存的属性">☀</a>2.缓存的属性</h4><p>​ eviction:表示缓存回收策略，默认是LRU</p><p>​ LRU：最近最少使用的，移除最长时间不被使用的对象</p><p>​ FIFO：先进先出，按照对象进入缓存的顺序来移除</p><p>​ SOFT：软引用，移除基于垃圾回收器状态和软引用规则的对象</p><p>​ WEAK：弱引用，更积极地移除基于垃圾收集器状态和弱引用规则的对象</p><p>​ flushInternal:刷新间隔，单位毫秒</p><p>​ 默认情况是不设置，也就是没有刷新间隔，缓存仅仅调用语句时刷新</p><p>​ size：引用数目，正整数</p><p>​ 代表缓存最多可以存储多少个对象，太大容易导致内存溢出</p><p>​ readonly：只读，true/false</p><p>​ true：只读缓存，会给所有调用这返回缓存对象的相同实例，因此这些对象不能被修改。</p><p>​ false：读写缓存，会返回缓存对象的拷贝（序列化实现），这种方式比较安全，默认值</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//可以看到会去二级缓存中查找数据，而且二级缓存跟一级缓存中不会同时存在数据，因为二级缓存中的数据是在sqlsession 关闭之后才生效的</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test05</span><span class="params">()</span>&#123;</span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno);</span><br><span class="line">       sqlSession.close();</span><br><span class="line"></span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession2</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="type">EmpDao</span> <span class="variable">mapper2</span> <span class="operator">=</span> sqlSession2.getMapper(EmpDao.class);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno2</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno2);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno3</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno3);</span><br><span class="line">       sqlSession2.close();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 缓存查询的顺序是先查询二级缓存再查询一级缓存</span></span><br><span class="line">	<span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test05</span><span class="params">()</span>&#123;</span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="type">EmpDao</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(EmpDao.class);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno</span> <span class="operator">=</span> mapper.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno);</span><br><span class="line">       sqlSession.close();</span><br><span class="line"></span><br><span class="line">       <span class="type">SqlSession</span> <span class="variable">sqlSession2</span> <span class="operator">=</span> sqlSessionFactory.openSession();</span><br><span class="line">       <span class="type">EmpDao</span> <span class="variable">mapper2</span> <span class="operator">=</span> sqlSession2.getMapper(EmpDao.class);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno2</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno2);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno3</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">1111</span>);</span><br><span class="line">       System.out.println(empByEmpno3);</span><br><span class="line"></span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno4</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">7369</span>);</span><br><span class="line">       System.out.println(empByEmpno4);</span><br><span class="line">       <span class="type">Emp</span> <span class="variable">empByEmpno5</span> <span class="operator">=</span> mapper2.findEmpByEmpno(<span class="number">7369</span>);</span><br><span class="line">       System.out.println(empByEmpno5);</span><br><span class="line">       sqlSession2.close();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>3、二级缓存的作用范围：</p><p>​ 如果设置了全局的二级缓存配置，那么在使用的时候需要注意，在每一个单独的select语句中，可以设置将查询缓存关闭，以完成特殊的设置</p><p>​ 1、在setting中设置，是配置二级缓存开启，一级缓存默认一直开启</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;cacheEnabled&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure><p>​ 2、select标签的useCache属性：</p><p>​ 在每一个select的查询中可以设置当前查询是否要使用二级缓存，只对二级缓存有效</p><p>​ 3、sql标签的flushCache属性</p><p>​ 增删改操作默认值为true，sql执行之后会清空一级缓存和二级缓存，而查询操作默认是false</p><p>​ 4、sqlSession.clearCache()</p><p>​ 只是用来清楚一级缓存</p><h4 id="3-整合第三方缓存"><a class="header-anchor" href="#3-整合第三方缓存">☀</a>3.整合第三方缓存</h4><p>​ 在某些情况下我们也可以自定义实现缓存，或为其他第三方缓存方案创建适配器，来完全覆盖缓存行为。</p><p>​ 1、导入对应的maven依赖</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.ehcache/ehcache --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.ehcache<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>ehcache<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.8.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis.caches<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-ehcache<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>slf4j-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.0-alpha1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>slf4j-log4j12<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.0-alpha1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p>​ 2、导入ehcache配置文件</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">ehcache</span> <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag"> <span class="attr">xsi:noNamespaceSchemaLocation</span>=<span class="string">&quot;http://ehcache.org/ehcache.xsd&quot;</span>&gt;</span></span><br><span class="line"> <span class="comment">&lt;!-- 磁盘保存路径 --&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">diskStore</span> <span class="attr">path</span>=<span class="string">&quot;D:\ehcache&quot;</span> /&gt;</span></span><br><span class="line"></span><br><span class="line"> <span class="tag">&lt;<span class="name">defaultCache</span></span></span><br><span class="line"><span class="tag">   <span class="attr">maxElementsInMemory</span>=<span class="string">&quot;1&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">maxElementsOnDisk</span>=<span class="string">&quot;10000000&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">eternal</span>=<span class="string">&quot;false&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">overflowToDisk</span>=<span class="string">&quot;true&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">timeToIdleSeconds</span>=<span class="string">&quot;120&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">timeToLiveSeconds</span>=<span class="string">&quot;120&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">diskExpiryThreadIntervalSeconds</span>=<span class="string">&quot;120&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">memoryStoreEvictionPolicy</span>=<span class="string">&quot;LRU&quot;</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">defaultCache</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ehcache</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">属性说明：</span></span><br><span class="line"><span class="comment">l diskStore：指定数据在磁盘中的存储位置。</span></span><br><span class="line"><span class="comment">l defaultCache：当借助CacheManager.add(&quot;demoCache&quot;)创建Cache时，EhCache便会采用&lt;defalutCache/&gt;指定的的管理策略</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">以下属性是必须的：</span></span><br><span class="line"><span class="comment">l maxElementsInMemory - 在内存中缓存的element的最大数目</span></span><br><span class="line"><span class="comment">l maxElementsOnDisk - 在磁盘上缓存的element的最大数目，若是0表示无穷大</span></span><br><span class="line"><span class="comment">l eternal - 设定缓存的elements是否永远不过期。如果为true，则缓存的数据始终有效，如果为false那么还要根据timeToIdleSeconds，timeToLiveSeconds判断</span></span><br><span class="line"><span class="comment">l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">以下属性是可选的：</span></span><br><span class="line"><span class="comment">l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时，这些数据便会删除，默认值是0,也就是可闲置时间无穷大</span></span><br><span class="line"><span class="comment">l timeToLiveSeconds - 缓存element的有效生命期，默认是0.,也就是element存活时间无穷大</span></span><br><span class="line"><span class="comment"> diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.</span></span><br><span class="line"><span class="comment">l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据，默认是false。</span></span><br><span class="line"><span class="comment">l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔，默认是120秒。每个120s，相应的线程会进行一次EhCache中数据的清理工作</span></span><br><span class="line"><span class="comment">l memoryStoreEvictionPolicy - 当内存缓存达到最大，有新的element加入的时候， 移除缓存中element的策略。默认是LRU（最近最少使用），可选的有LFU（最不常使用）和FIFO（先进先出）</span></span><br><span class="line"><span class="comment"> --&gt;</span></span><br></pre></td></tr></table></figure><p>​ 3、在mapper文件中添加自定义缓存</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">cache</span> <span class="attr">type</span>=<span class="string">&quot;org.mybatis.caches.ehcache.EhcacheCache&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">cache</span>&gt;</span></span><br></pre></td></tr></table></figure><div class="footer"><div class="copyright"><blockquote><p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</p><p>本文永久链接是：<a href="http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/">http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/</a></p></blockquote></div></div><div class="article-meta" id="bottom"><div class="new-meta-box"><div class="new-meta-item date" itemprop="dateUpdated" datetime="2021-03-01T10:52:06+08:00"><a class="notlink"><i class="fas fa-edit fa-fw" aria-hidden="true"></i><p>更新于：2021年3月1日</p></a></div><div class="new-meta-item meta-tags"><a class="tag" href="/tags/Mybatis/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>Mybatis</p></a></div><div class="new-meta-item share -mob-share-list"><div class="-mob-share-list share-body"> <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer noopener" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/&title=Mybatis学习笔记2-映射文件 - Tang's blog.&summary=cache – 该命名空间的缓存配置。
cache-ref – 引用其它命名空间的缓存配置。
resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。
parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。
sql – 可被其它语句引用的可重用语句块。
insert – 映射插入语句。
update – 映射更新语句。
delete – 映射删除语句。
select – 映射查询语句。"><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" srcset=""></a> <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer noopener" target="_blank" href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/&title=Mybatis学习笔记2-映射文件 - Tang's blog.&summary=cache – 该命名空间的缓存配置。
cache-ref – 引用其它命名空间的缓存配置。
resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。
parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。
sql – 可被其它语句引用的可重用语句块。
insert – 映射插入语句。
update – 映射更新语句。
delete – 映射删除语句。
select – 映射查询语句。"><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" srcset=""></a> <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer noopener" target="_blank" href="http://service.weibo.com/share/share.php?url=http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/&title=Mybatis学习笔记2-映射文件 - Tang's blog.&summary=cache – 该命名空间的缓存配置。
cache-ref – 引用其它命名空间的缓存配置。
resultMap – 描述如何从数据库结果集中加载对象，是最复杂也是最强大的元素。
parameterMap – 老式风格的参数映射。此元素已被废弃，并可能在将来被移除！请使用行内参数映射。文档中不会介绍此元素。
sql – 可被其它语句引用的可重用语句块。
insert – 映射插入语句。
update – 映射更新语句。
delete – 映射删除语句。
select – 映射查询语句。"><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" srcset=""></a><div class="hoverbox"> <a class="share"><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/wechat.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/wechat.png" srcset=""></a><div class="target"> <img src=""></div></div> <a class="-mob-share-telegram" title="" rel="external nofollow noopener noreferrer noopener" target="_blank" href="https://t.me/share/url?url=http://aner1001.gitee.io/posts/2021/03/01/10b37d7d655c/&text=Mybatis学习笔记2-映射文件 - Tang's blog."><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/telegram.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/telegram.png" srcset=""></a></div></div></div></div><div class="prev-next"><a class="prev" href="/posts/2021/03/01/918150132c1d/"><p class="title"><i class="fas fa-chevron-left" aria-hidden="true"></i>Mybatis学习笔记3-整合与逆向工程</p><p class="content"> 三大框架整合. mybatis逆向工程 ☀1.三大框架整合 ​ 在老期的项目中，一般都是使用ssm项目做开发的，虽然现在的主流开发是springboot来做开发，但是ssm的基本整合还是...</p></a><a class="next" href="/posts/2021/02/28/07b533182cc8/"><p class="title">Mybatis学习笔记1-介绍和基本使用<i class="fas fa-chevron-right" aria-hidden="true"></i></p><p class="content">MyBatis 是一款优秀的持久层框架，它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的...</p></a></div></article><article class="post white-box reveal shadow" id="comments"><p ct><i class="fas fa-comments"></i> 评论</p><div id="valine_container" class="valine_thread"><i class="fas fa-cog fa-spin fa-fw fa-2x"></i></div></article></div><aside class="l_side"><section class="widget list group shadow desktop mobile"><header><a target="_blank" rel="noopener external nofollow noreferrer" href="http://mybatis.org/"><i class="fab fa-github fa-fw" aria-hidden="true"></i> <span class="name">Mybatis</span></a></header><div class="content"><ul class="list entry navigation"><li><a class="flat-box" title="/posts/2021/02/28/07b533182cc8/" href="/posts/2021/02/28/07b533182cc8/" id="posts2021022807b533182cc8"><div class="name"> Mybatis学习笔记1-介绍和基本使用</div></a></li><li><a class="flat-box" title="/posts/2021/03/01/10b37d7d655c/" href="/posts/2021/03/01/10b37d7d655c/" id="posts2021030110b37d7d655c"><div class="name"> Mybatis学习笔记2-映射文件</div></a></li><li><a class="flat-box" title="/posts/2021/03/01/918150132c1d/" href="/posts/2021/03/01/918150132c1d/" id="posts20210301918150132c1d"><div class="name"> Mybatis学习笔记3-整合与逆向工程</div></a></li><li><a class="flat-box" title="/posts/2021/03/01/a33259cdd98b/" href="/posts/2021/03/01/a33259cdd98b/" id="posts20210301a33259cdd98b"><div class="name"> Mybatis学习笔记4-使用mybatis-plus</div></a></li></ul></div></section><section class="widget toc-wrapper shadow desktop mobile" id="toc-div"><header><i class="fas fa-list fa-fw" aria-hidden="true"></i> <span class="name">本文目录</span></header><div class="content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-insert%E3%80%81update%E3%80%81delete%E5%85%83%E7%B4%A0"><span class="toc-text">1.insert、update、delete元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-select%E5%85%83%E7%B4%A0"><span class="toc-text">2.select元素</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-select%E7%9A%84%E5%8F%82%E6%95%B0%E4%BC%A0%E9%80%92"><span class="toc-text">1.select的参数传递</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%8F%82%E6%95%B0%E7%9A%84%E5%8F%96%E5%80%BC%E6%96%B9%E5%BC%8F"><span class="toc-text">2.参数的取值方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%A4%84%E7%90%86%E9%9B%86%E5%90%88%E8%BF%94%E5%9B%9E%E7%BB%93%E6%9E%9C"><span class="toc-text">3.处理集合返回结果</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%93%E6%9E%9C%E9%9B%86%E2%80%94resultMap"><span class="toc-text">4.自定义结果集—resultMap</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E8%81%94%E5%90%88%E6%9F%A5%E8%AF%A2"><span class="toc-text">5.联合查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E8%8E%B7%E5%8F%96%E9%9B%86%E5%90%88%E5%85%83%E7%B4%A0"><span class="toc-text">6.获取集合元素</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E5%88%86%E6%AD%A5%E6%9F%A5%E8%AF%A2"><span class="toc-text">7.分步查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%BB%B6%E8%BF%9F%E6%9F%A5%E8%AF%A2"><span class="toc-text">8.延迟查询</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%8A%A8%E6%80%81sql"><span class="toc-text">3.动态sql</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-if"><span class="toc-text">1.if</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-foreach"><span class="toc-text">2.foreach</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-choose"><span class="toc-text">3.choose</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-set"><span class="toc-text">4.set</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E7%BC%93%E5%AD%98"><span class="toc-text">4.缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">1.一级缓存的使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-text">2.二级缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E7%BC%93%E5%AD%98%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">1.缓存的使用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E7%BC%93%E5%AD%98%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="toc-text">2.缓存的属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E6%95%B4%E5%90%88%E7%AC%AC%E4%B8%89%E6%96%B9%E7%BC%93%E5%AD%98"><span class="toc-text">3.整合第三方缓存</span></a></li></ol></li></ol></li></ol></div></section></aside><script>window.pdata={},pdata.ispage=!0,pdata.postTitle="Mybatis学习笔记2-映射文件",pdata.commentPath="",pdata.commentPlaceholder="";var l_header=document.getElementById("l_header");l_header.classList.add("show");var cover_wrapper=document.querySelector(".cover-wrapper");cover_wrapper.id="none",cover_wrapper.style.display="none"</script></div><footer class="footer clearfix"><br><br><div class="aplayer-container"><meting-js theme="#1BCDFC" autoplay="false" volume="0.7" loop="all" order="list" fixed="false" list-max-height="320px" server="netease" type="playlist" id="5472211102" list-folded="true"></meting-js></div><br><div class="social-wrapper"><a href="/atom.xml" class="social fas fa-rss flat-btn" target="_blank" rel="external nofollow noopener noreferrer"></a><a href="mailto:584856024@qq.com" class="social fas fa-envelope flat-btn" target="_blank" rel="external nofollow noopener noreferrer"></a><a href="https://github.com/aner1001" class="social fab fa-github flat-btn" target="_blank" rel="external nofollow noopener noreferrer"></a><a href="https://music.163.com/#/user/home?id=1402271985" class="social fas fa-headphones-alt flat-btn" target="_blank" rel="external nofollow noopener noreferrer"></a></div><div><p>博客内容遵循 <a target="_blank" rel="noopener external nofollow noreferrer" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p></div><div><p><span id="lc-sv">本站总访问量为<span id="number"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 次</span> <span id="lc-uv">访客数为<span id="number"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 人</span></p></div> 本站使用 <a href="https://github.com/volantis-x/hexo-theme-volantis/tree/4.3.1" rel="external nofollow noreferrer" target="_blank" class="codename">Volantis</a> 作为主题，总访问量为<span id="busuanzi_value_site_pv"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 次<div class="copyright"><p><a href="/">Copyright © 2021-2021 XXX</a></p></div></footer><a id="s-top" class="fas fa-arrow-up fa-fw" href="javascript:void(0)" rel="external nofollow noreferrer"></a></div></div><div><script>function VPjax(){function e(e,t){this.name=t||e.name,this.run=()=>{e()}}this.list=[],this.start=()=>{for(var e=0;e<this.list.length;e++)this.list[e].run()},this.push=(t,n)=>{var i=new e(t,n);this.list.push(i)}}function loadScript(e,t){setTimeout((function(){var n=document.getElementsByTagName("head")[0]||document.documentElement,i=document.createElement("script");i.setAttribute("type","text/javascript"),t&&(i.onload=t),i.setAttribute("src",e),n.appendChild(i)}))}window.volantis={},window.volantis.loadcss=document.getElementById("loadcss"),volantis.pjax={},volantis.pjax.method={complete:new VPjax,error:new VPjax,send:new VPjax},volantis.pjax={...volantis.pjax,push:volantis.pjax.method.complete.push,error:volantis.pjax.method.error.push,send:volantis.pjax.method.send.push};var loadCSS=function(e,t,n,i){var o,a=window.document,s=a.createElement("link");if(t)o=t;else{var r=(a.body||a.getElementsByTagName("head")[0]).childNodes;o=r[r.length-1]}var d=a.styleSheets;if(i)for(var l in i)i.hasOwnProperty(l)&&s.setAttribute(l,i[l]);s.rel="stylesheet",s.href=e,s.media="only x",function e(t){if(a.body)return t();setTimeout((function(){e(t)}))}((function(){o.parentNode.insertBefore(s,t?o:o.nextSibling)}));var u=function(e){for(var t=s.href,n=d.length;n--;)if(d[n].href===t)return e();setTimeout((function(){u(e)}))};function h(){s.addEventListener&&s.removeEventListener("load",h),s.media=n||"all"}return s.addEventListener&&s.addEventListener("load",h),s.onloadcssdefined=u,u(h),s}</script><script>loadCSS("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css",window.volantis.loadcss),loadCSS("https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css",window.volantis.loadcss),loadCSS("https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css",window.volantis.loadcss)</script><script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script><script>function pjax_fancybox(){$(".md .gallery").find("img").each((function(){var a=document.createElement("a");$(a).attr("class","fancybox"),$(a).attr("pjax-fancybox",""),$(a).attr("href",$(this).attr("src")),$(this).attr("data-original")&&$(a).attr("href",$(this).attr("data-original")),$(a).attr("data-fancybox","images");var t="";$(this).attr("alt")&&($(a).attr("data-caption",$(this).attr("alt")),t=$(this).attr("alt"));var n=document.createElement("div");$(n).addClass("fancybox"),$(this).wrap(n);var o=document.createElement("span");$(o).addClass("image-caption"),$(o).text(t),$(this).after(o),$(this).wrap(a)})),$(".md .gallery").find("img").fancybox({selector:'[data-fancybox="images"]',hash:!1,loop:!1,closeClick:!0,helpers:{overlay:{closeClick:!0}},buttons:["zoom","close"]})}function SCload_fancybox(){0!=$(".md .gallery").find("img").length&&(loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css",document.getElementById("loadcss")),loadScript("https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js",pjax_fancybox))}function Pjax_SCload_fancybox(){void 0===$.fancybox?SCload_fancybox():pjax_fancybox()}$((function(){SCload_fancybox()})),volantis.pjax.push(Pjax_SCload_fancybox),volantis.pjax.send(()=>{void 0!==$.fancybox&&$.fancybox.close()},"fancybox")</script><script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script><script type="text/javascript">var imgs=["https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/001.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/002.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/003.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/004.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/005.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/006.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/012.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/016.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/019.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/025.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/033.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/034.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/035.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/038.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/039.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/042.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/046.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/051.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/052.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/054.jpg","https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/056.jpg"];{function shuffle(t){for(var n=t.length;n--;){var i=Math.floor(Math.random()*n),l=t[i];t[i]=t[n],t[n]=l}}shuffle(imgs)}function Pjax_backstretch(){$("#cover-backstretch").backstretch(imgs,{duration:"10000",fade:"1500"})}loadScript("https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js",Pjax_backstretch)</script><div id="rightmenu-wrapper"><ul class="list-v rightmenu" id="rightmenu-content"><li class="option"><a class="vlts-menu opt fix-cursor-default" id="menu-copy-text" onclick='document.execCommand("copy")'><i class="fa fa-copy fa-fw"></i> 复制文本</a><hr id="hr-text"><a class="vlts-menu opt fix-cursor-default" id="menu-copy-href"><i class="fa fa-link fa-fw"></i> 复制链接</a><a class="vlts-menu opt fix-cursor-default" id="menu-open-href"><i class="fa fa-external-link-square-alt fa-fw"></i> 在新标签页打开</a><hr id="hr-href"><a class="vlts-menu opt fix-cursor-default" id="menu-copy-src"><i class="fa fa-image fa-fw"></i> 复制图片地址</a><hr id="hr-src"></li><li class="navigation"><a class="nav icon-only fix-cursor-default" onclick="history.back()"><i class="fa fa-arrow-left fa-fw"></i></a><a class="nav icon-only fix-cursor-default" onclick="history.forward()"><i class="fa fa-arrow-right fa-fw"></i></a><a class="nav icon-only fix-cursor-default" onclick="window.location.reload()"><i class="fa fa-redo fa-fw"></i></a><a class="nav icon-only fix-cursor-default" href="/"><i class="fa fa-home fa-fw"></i></a></li><hr><li><a class="vlts-menu fix-cursor-default" href="https://volantis.js.org/faqs/" id="https:volantisjsorgfaqs"><i class="fa fa-question fa-fw"></i> 常见问题</a></li><li><a class="vlts-menu fix-cursor-default" href="https://volantis.js.org/examples/" id="https:volantisjsorgexamples"><i class="fa fa-rss fa-fw"></i> 示例博客</a></li><li><a class="vlts-menu fix-cursor-default" href="https://volantis.js.org/contributors/" id="https:volantisjsorgcontributors"><i class="fa fa-fan fa-spin fa-fw"></i> 加入社区</a></li><hr><li><a class="vlts-menu fix-cursor-default" href="https://github.com/volantis-x/volantis-docs/" id="https:githubcomvolantis-xvolantis-docs"><i class="fa fa-code-branch fa-fw"></i> 本站源码</a></li><li><a class="vlts-menu fix-cursor-default" href="https://github.com/volantis-x/hexo-theme-volantis/" id="https:githubcomvolantis-xhexo-theme-volantis"><i class="fa fa-code-branch fa-fw"></i> 主题源码</a></li><hr><li><a class="vlts-menu fix-cursor-default" onclick='document.execCommand("print")'><i class="fa fa-print fa-fw"></i> 打印页面</a></li><hr><li><a class="vlts-menu fix-cursor-default toggle-mode-btn"><i class="fas fa-moon fa-fw"></i> Dark</a></li><hr><li class="music name"><p class="nav music-title fix-cursor-default"></p></li><li class="music ctrl"><a class="nav icon-only backward fix-cursor-default" onclick="aplayerBackward()"><i class="fa fa-step-backward fa-fw"></i></a><a class="nav icon-only toggle fix-cursor-default" onclick="aplayerToggle()"><i class="fa fa-play fa-fw"></i></a><a class="nav icon-only forward fix-cursor-default" onclick="aplayerForward()"><i class="fa fa-step-forward fa-fw"></i></a></li><li class="music volume"><a class="nav volume"><div class="aplayer-volume-bar-wrap"><div class="aplayer-volume-bar fix-cursor-pointer"><div class="aplayer-volume"></div><i class="left fa fa-volume-off fa-fw"></i><i class="right fa fa-volume-up fa-fw"></i></div></div></a></li></ul></div><script>function popMenu(e){var t=document.getElementById("rightmenu-wrapper"),n=document.getElementById("rightmenu-content"),l=document.documentElement.clientWidth||document.body.clientWidth,o=document.documentElement.clientHeight||document.body.clientHeight;t.style.left=e.clientX+"px",t.style.top=e.clientY+"px",t.style.display="block",2*e.clientX>l?n.classList.add("left"):n.classList.remove("left"),2*e.clientY>o?n.classList.add("top"):n.classList.remove("top");let c=document.getElementById("hr-text"),d=document.getElementById("hr-src"),y=document.getElementById("hr-href"),s=document.getElementById("menu-copy-src");null!=s&&(e.target.currentSrc?(s.style.display="block",s.addEventListener("click",(function(t){copyString(e.target.currentSrc)}),{once:!0}),d.style.display="block"):(s.style.display="none",d.style.display="none"));let r="";if(e.path)for(i=0;i<e.path.length;i++)null!=e.path[i].href&&e.path[i].href.length>0&&(r=e.path[i].href);let u=document.getElementById("menu-copy-text");u.style.display="none",c.style.display="none",0==r.length&&window.getSelection().toString()&&(u.style.display="block",c.style.display="block");let m=document.getElementById("menu-open-href");null!=m&&(r.length>0?(m.style.display="block",m.addEventListener("click",(function(e){window.open(r)}),{once:!0}),y.style.display="block"):(m.style.display="none",y.style.display="none"));let a=document.getElementById("menu-copy-href");return null!=a&&(r.length>0?(a.style.display="block",a.addEventListener("click",(function(e){copyString(r)}),{once:!0})):a.style.display="none"),volantis.APlayerLoaded&&checkAPlayer(),!1}function hideMenu(){document.getElementById("rightmenu-wrapper").style.display="none"}function copyString(e){const t=document.createElement("input");t.setAttribute("readonly","readonly"),document.body.appendChild(t),t.setAttribute("value",e),t.select(),document.execCommand("copy"),document.body.removeChild(t)}window.document.oncontextmenu=function(e){return!!e.ctrlKey||(!!/Android|webOS|BlackBerry/i.test(navigator.userAgent)||popMenu(e))},document.addEventListener("click",(function(e){document.getElementById("rightmenu-wrapper").style.display="none"})),document.execCommand("click")</script><script>function loadIssuesJS(){0!=$(".md").find(".issues-api").length&&loadScript("https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.3.1/source/js/issues.min.js")}$((function(){loadIssuesJS()})),volantis.pjax.push(()=>{"undefined"==typeof IssuesAPI&&loadIssuesJS()},"IssuesJS")</script><script defer="defer" src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script><script>window.lazyLoadOptions={elements_selector:".lazyload",threshold:0},window.addEventListener("LazyLoad::Initialized",(function(n){window.lazyLoadInstance=n.detail.instance}),!1),document.addEventListener("DOMContentLoaded",(function(){lazyLoadInstance.update()})),document.addEventListener("pjax:complete",(function(){lazyLoadInstance.update()}))</script><script>window.FPConfig={delay:0,ignoreKeywords:[],maxRPS:5,hoverDelay:25}</script><script defer="defer" src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script><script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script><script>var clipboard=new ClipboardJS(".btn-copy",{target:function(e){return e.nextElementSibling}});function wait(e,i){window.setTimeout(e,i)}function pjax_initCopyCode(){if($(".highlight .code pre").length+$(".article pre code").length!=0){var e="";e+='<button class="btn-copy" data-clipboard-snippet="">',e+='<i class="fas fa-copy"></i><span>COPY</span>',e+="</button>",$(".highlight .code pre").before(e),$(".article pre code").before(e),clipboard.off("success").on("success",(function(e){let i=$(e.trigger);i.addClass("copied");let a=$(i.find("i"));a.removeClass("fa-copy"),a.addClass("fa-check-circle");let n=$(i.find("span"));n[0].innerText="COPIED",wait((function(){a.removeClass("fa-check-circle"),a.addClass("fa-copy"),n[0].innerText="COPY"}),2e3)})),clipboard.off("error").on("error",(function(e){e.clearSelection();let i=$(e.trigger);i.addClass("copy-failed");let a=$(i.find("i"));a.removeClass("fa-copy"),a.addClass("fa-times-circle");let n=$(i.find("span"));n[0].innerText="COPY FAILED",wait((function(){a.removeClass("fa-times-circle"),a.addClass("fa-copy"),n[0].innerText="COPY"}),2e3)}))}}$((function(){pjax_initCopyCode()})),volantis.pjax.push(pjax_initCopyCode)</script><script type="text/javascript">function pjax_scrollrebeal(){ScrollReveal().reveal(".l_main .reveal",{distance:"32px",duration:"800",interval:"20",scale:"1",easing:"ease-out"})}loadScript("https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"),$((function(){var e=setInterval((function(){"block"==$("#safearea").css("display")&&"undefined"!=typeof ScrollReveal&&(clearInterval(e),pjax_scrollrebeal())}),100)})),volantis.pjax.push(pjax_scrollrebeal)</script><script>let APlayerController=new Object;APlayerController.id="5472211102",APlayerController.volume="0.7",loadCSS("https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.css",window.volantis.loadcss),loadScript("https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.js"),window.volantis.APlayerLoaded=0;var checkAPlayer=setInterval((function(){window.APlayer&&"block"==$("#safearea").css("display")&&(clearInterval(checkAPlayer),window.volantis.APlayerLoaded||window.MetingJSElement||(window.volantis.APlayerLoaded=1,loadScript("https://cdn.jsdelivr.net/npm/meting@2.0/dist/Meting.min.js")))}),2500);loadScript("https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.3.1/source/js/aplayer.min.js")</script><script src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.3.1/source/js/valine.min.js"></script><script>function emoji(i,e,a){return i+"/"+i+"-"+e+"."+a}for(var emojiMaps={},i=1;i<=54;i++)emojiMaps["tieba-"+i]=emoji("tieba",i,"png");for(i=1;i<=101;i++)emojiMaps["qq-"+i]=emoji("qq",i,"gif");for(i=1;i<=116;i++)emojiMaps["aru-"+i]=emoji("aru",i,"gif");for(i=1;i<=125;i++)emojiMaps["twemoji-"+i]=emoji("twemoji",i,"png");for(i=1;i<=4;i++)emojiMaps["weibo-"+i]=emoji("weibo",i,"png");function pjax_valine(){if(!document.querySelectorAll("#valine_container")[0])return;let i=pdata.commentPlaceholder||"快来评论吧~",e=pdata.commentPath;if(0==e.length){e=""||decodeURI(window.location.pathname)}(new Valine).init(Object.assign({path:null,placeholder:"快来评论吧~",appId:"eL9fCmXLl3nAe225XYo1cRxj-MdYXbMMI",appKey:"5uTd5Uu8WJJIej6Efrivsvaa",meta:["nick","mail","link"],requiredFields:["nick","mail"],enableQQ:!0,recordIP:!1,avatar:"robohash",pageSize:10,lang:"zh-cn",highlight:!0,mathJax:!1},{el:"#valine_container",path:e,placeholder:i,emojiCDN:"https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/",emojiMaps:emojiMaps}))}$((function(){pjax_valine()})),volantis.pjax.push(pjax_valine)</script><script defer="defer" src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js" data-pjax></script><script src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.3.1/source/js/app.min.js"></script><script>const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/",ROOT="/".endsWith("/")?"/":"//";function listenSearch(){customSearch=new HexoSearch({imagePath:SearchServiceimagePath})}function setSearchService(){listenSearch()}$(".input.u-search-input").one("focus",(function(){loadScript("https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2.6.4/js/search.js",setSearchService)}))</script><script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script><script type="text/javascript">$((function(){Waves.attach(".flat-btn",["waves-button"]),Waves.attach(".float-btn",["waves-button","waves-float"]),Waves.attach(".float-btn-light",["waves-button","waves-float","waves-light"]),Waves.attach(".flat-box",["waves-block"]),Waves.attach(".float-box",["waves-block","waves-float"]),Waves.attach(".waves-image"),Waves.init()}))</script><script src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2/js/comment_typing.js"></script><script defer="defer">const LCCounter={app_id:"C2dIVXJ48qC7eHgvQRId6niR-MdYXbMMI",app_key:"1956OGJ4LQhDxheBAO5WhPJn",custom_api_server:"",getRecord:(e,t,r)=>new Promise((function(n,i){e("get","/classes/Counter?where="+encodeURIComponent(JSON.stringify({url:t}))).then(e=>e.json()).then(({results:o,code:s,error:a})=>{if(401===s)throw a;if(o&&o.length>0){var l=o[0];n(l)}else e("post","/classes/Counter",{url:t,title:r,times:0}).then(e=>e.json()).then((e,t)=>{if(t)throw t;n(e)}).catch(e=>{console.error("Failed to create",e),i(e)})}).catch(e=>{console.error("LeanCloud Counter Error:",e),i(e)})})),increment:(e,t)=>new Promise((function(r,n){e("post","/batch",{requests:t}).then(e=>{if((e=e.json()).error)throw e.error;r(e)}).catch(e=>{console.error("Failed to save visitor count",e),n(e)})})),buildIncrement:e=>({method:"PUT",path:"/1.1/classes/Counter/"+e,body:{times:{__op:"Increment",amount:1}}}),validUV(){var e="LeanCloudUVTimestamp",t=localStorage.getItem(e);return!(t&&(new Date).getTime()-parseInt(t)<=864e5)&&(localStorage.setItem(e,(new Date).getTime().toString()),!0)},addCount(e){var t=[],r=[],n=document.querySelector("#lc-sv"),o=this.getRecord(e,"http://aner1001.gitee.io/#lc-sv","Visits").then(e=>{r.push(this.buildIncrement(e.objectId));var t=document.querySelectorAll("#lc-sv #number");t.length>0&&t.forEach((t,r,i)=>{t.innerText=e.times+1,n&&(n.style.display="inline")})});t.push(o);var s=document.querySelector("#lc-uv"),a=this.getRecord(e,"http://aner1001.gitee.io/#lc-uv","Visitors").then(e=>{var t=this.validUV();t&&r.push(this.buildIncrement(e.objectId));var n=document.querySelectorAll("#lc-uv #number");n.length>0&&n.forEach((r,n,i)=>{r.innerText=e.times+(t?1:0),s&&(s.style.display="inline")})});t.push(a);var l=document.querySelectorAll("#lc-pv");for(l.length,i=0;i<l.length;i++){let n=l[i],o=n.getAttribute("data-title");var h="http://aner1001.gitee.io"+n.getAttribute("data-path");if(h){var c=this.getRecord(e,h,o).then(e=>{let t=window.location.pathname;if(t.includes("index.html")&&(t=t.substring(0,t.lastIndexOf("index.html"))),n.getAttribute("data-path")==t&&r.push(this.buildIncrement(e.objectId)),n){var i=n.querySelector("#lc-pv #number");i&&(n.getAttribute("data-path")==t?i.innerText=(e.times||0)+1:i.innerText=e.times||0,n.style.display="inline")}});t.push(c)}}Promise.all(t).then(()=>{r.length>0&&this.increment(e,r)})},fetchData(e){this.addCount((t,r,n)=>fetch(`${e}/1.1${r}`,{method:t,headers:{"X-LC-Id":this.app_id,"X-LC-Key":this.app_key,"Content-Type":"application/json"},body:JSON.stringify(n)}))},refreshCounter(){var e="-MdYXbMMI"!==this.app_id.slice(-9)?this.custom_api_server:`https://${this.app_id.slice(0,8).toLowerCase()}.api.lncldglobal.com`;e?this.fetchData(e):fetch("https://app-router.leancloud.cn/2/route?appId="+this.app_id).then(e=>e.json()).then(({api_server:e})=>{this.fetchData("https://"+e)})}};LCCounter.refreshCounter(),document.addEventListener("pjax:complete",(function(){LCCounter.refreshCounter()}))</script><script>const rootElement=document.documentElement,darkModeStorageKey="user-color-scheme",rootElementDarkModeAttributeName="data-user-color-scheme",setLS=(e,t)=>{localStorage.setItem(e,t)},removeLS=e=>{localStorage.removeItem(e)},getLS=e=>localStorage.getItem(e),getModeFromCSSMediaQuery=()=>window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",resetRootDarkModeAttributeAndLS=()=>{var e;rootElement.removeAttribute("data-user-color-scheme"),e=darkModeStorageKey,localStorage.removeItem(e)},validColorModeKeys={dark:!0,light:!0},applyCustomDarkModeSettings=e=>{const t=e||getLS(darkModeStorageKey);t===getModeFromCSSMediaQuery()?resetRootDarkModeAttributeAndLS():validColorModeKeys[t]?rootElement.setAttribute("data-user-color-scheme",t):resetRootDarkModeAttributeAndLS()},invertDarkModeObj={dark:"light",light:"dark"},toggleCustomDarkMode=()=>{let e=getLS(darkModeStorageKey);if(validColorModeKeys[e])e=invertDarkModeObj[e];else{if(null!==e)return;e=invertDarkModeObj[getModeFromCSSMediaQuery()]}var t,o;return t=darkModeStorageKey,o=e,localStorage.setItem(t,o),e};var btn=$("#wrapper .toggle-mode-btn,#rightmenu-wrapper .toggle-mode-btn");function bindToggleButton(){btn.on("click",e=>{const t=toggleCustomDarkMode();applyCustomDarkModeSettings(t)})}applyCustomDarkModeSettings(),document.addEventListener("DOMContentLoaded",bindToggleButton),volantis.pjax.push(bindToggleButton),volantis.pjax.send(()=>{btn.unbind("click")},"toggle-mode-btn-unbind")</script><script>function listennSidebarTOC(){const e=document.querySelectorAll(".toc li");if(!e.length)return;const t=[...e].map(e=>{const t=e.querySelector(".toc-link"),n=document.getElementById(decodeURI(t.getAttribute("href")).replace("#",""));return t.addEventListener("click",e=>{e.preventDefault(),window.scrollTo({top:n.offsetTop+100,behavior:"smooth"})}),n});!function n(o){o=Math.floor(o+1e4);let r=new IntersectionObserver((r,c)=>{let i=document.documentElement.scrollHeight+100;if(i>o)return c.disconnect(),void n(i);let l=function(e){let n=0,o=e[n];if(o.boundingClientRect.top>0)return n=t.indexOf(o.target),0===n?0:n-1;for(;n<e.length;n++){if(!(e[n].boundingClientRect.top<=0))return t.indexOf(o.target);o=e[n]}return t.indexOf(o.target)}(r);!function(e){if(e.classList.contains("active-current"))return;document.querySelectorAll(".toc .active").forEach(e=>{e.classList.remove("active","active-current")}),e.classList.add("active","active-current");let t=e.parentNode;for(;!t.matches(".toc");)t.matches("li")&&t.classList.add("active"),t=t.parentNode}(e[l])},{rootMargin:o+"px 0px -100% 0px",threshold:0});t.forEach(e=>{e&&r.observe(e)})}(document.documentElement.scrollHeight)}document.addEventListener("DOMContentLoaded",listennSidebarTOC),document.addEventListener("pjax:success",listennSidebarTOC)</script><script>"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then((function(e){e.onupdatefound=function(){var r=e.installing;r.onstatechange=function(){switch(r.state){case"installed":navigator.serviceWorker.controller?console.log("Updated serviceWorker."):console.log("serviceWorker Sucess!");break;case"redundant":console.log("The installing service worker became redundant.")}}}})).catch((function(e){console.log("Error during service worker registration:",e)}))</script><script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script><div class="pjax-animate"><script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js"></script><div id="loading-bar-wrapper"><script>NProgress.configure({parent:"#loading-bar-wrapper",trickleSpeed:100})</script></div><script>window.ShowLoading=function(){NProgress.start()},window.HideLoading=function(){NProgress.done()}</script><script>volantis.pjax.push(window.HideLoading,"HideLoading"),volantis.pjax.send(window.ShowLoading,"ShowLoading"),volantis.pjax.error(window.HideLoading,"HideLoading")</script></div><script>var pjax;document.addEventListener("DOMContentLoaded",(function(){pjax=new Pjax({elements:'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',selectors:["title","#pjax-container","#pjax-header-nav-list"],cacheBust:!1,timeout:5e3})})),document.addEventListener("pjax:send",(function(e){try{var n=window.location.pathname,t=e.triggerElement.href,o=[""];""!=o[0]&&o.forEach(e=>{-1==n.indexOf(e)&&-1==t.indexOf(e)||(window.location.href=t)})}catch(e){}window.subData=null,volantis.$switcher.removeClass("active"),volantis.$header.removeClass("z_search-open"),volantis.$wrapper.removeClass("sub"),volantis.$topBtn.unbind("click"),$(".menu a").unbind("click"),$(window).unbind("resize"),$(window).unbind("scroll"),$(document).unbind("scroll"),$(document).unbind("click"),$("body").unbind("click"),volantis.pjax.method.send.start()})),document.addEventListener("pjax:complete",(function(){$(".nav-main").find(".list-v").not(".menu-phone").removeAttr("style",""),$(".menu-phone.list-v").removeAttr("style",""),$("script[data-pjax], .pjax-reload script").each((function(){$(this).parent().append($(this).remove())}));try{volantis.pjax.method.complete.start()}catch(e){console.log(e)}})),document.addEventListener("pjax:error",(function(e){volantis.pjax.method.error.start(),window.location.href=e.triggerElement.href}))</script></div></body></html>